import { VersionManageAPI } from '../common/type';
import { AutoComplete, Card, Empty, Input } from 'antd';
import { VersionDetailContext } from '../common/UpdateContext';
import { ChangeEvent, useContext, useEffect, useMemo, useState } from 'react';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { SearchOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import cls from 'classnames';
import {
  getCompanyID,
  getCompanyName,
  getUserDepID,
  getUserDepName,
} from '@/utils';
import MyIcon from '@/components/MyIcon';

export const DetailRightViewTop: React.FC<VersionManageAPI.IVersionDetailRightViewTop> = () => {
  const { prefixCls, getVersionDetailData, curRes } = useContext(
    VersionDetailContext,
  );

  /**
   * 保存右侧树搜索的值
   */
  const [seachValue, setSeachValue] = useState<string>('');

  /**
   * 渲染数据
   */
  const [receiveListMemo, setReceiveListMemo] = useState<any>([]);

  /**
   * 处理渲染数据
   */
  useEffect(() => {
    let list: any[] = [];
    if (getVersionDetailData?.viewRange == '0') {
      list =
        getVersionDetailData?.receiveList?.length > 0
          ? getVersionDetailData?.receiveList
          : [];
    } else {
      let obj: any = {
        receiveDepartmentID: getUserDepID(),
        receiveDepartmentName: getUserDepName(),
        receiveCompanyID: getCompanyID(),
        receiveCompanyName: getCompanyName(),
      };
      list?.push(obj);
    }
    setReceiveListMemo(list);
  }, [getVersionDetailData]);

  /**
   * 搜索下拉菜单
   */
  const autoOption = useMemo(() => {
    let option: Record<string, any>[] = [];
    const titleList = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        const name =
          item?.receiveDepartmentName +
          (item?.receiveCompanyName ? `（${item?.receiveCompanyName}）` : '');
        if (name?.includes(seachValue)) {
          // const nameLength = name?.length;
          // const select = name?.search(seachValue);
          // const searchLength = seachValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = seachValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.receiveDepartmentID,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    titleList(receiveListMemo);
    return option;
  }, [receiveListMemo, seachValue]);

  /**
   *  点击搜索
   * @param value
   * @param option
   */
  const onAutoSelect = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    setSeachValue(value);
    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };

  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setSeachValue(e.target.value);
  };

  /**
   * 滚动定位
   * @param id  滚动元素 id
   */
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  /**
   * 处理搜索变色
   * @param dataName
   * @param icon
   * @returns
   */
  const searchChangeStyle = (dataName: string, icon?: any) => {
    const name = dataName;
    const nameLength = name?.length;
    const select = name?.search(seachValue);
    const searchLength = seachValue?.length;
    const afterStr = name?.slice(0, select);
    const selectStr = seachValue;
    const beforeStr = name?.slice(select + searchLength, nameLength);
    const title =
      select > -1 && selectStr ? (
        <div>
          {icon}
          &nbsp;&nbsp;
          {afterStr}
          <span style={{ color: '#f50' }}>{selectStr}</span>
          {beforeStr}
        </div>
      ) : (
        <div>
          {icon}
          &nbsp;&nbsp;
          {dataName}
        </div>
      );
    return title;
  };

  return (
    <div className={prefixCls + 'rightBoxView-headerBox'}>
      <div className={prefixCls + 'row-col-divBox'}>
        <Card
          title="接收部门"
          className={cls(
            pageStyles['page-view'],
            pageStyles['searchExtra'],
            prefixCls + 'CardAutoComplete',
            prefixCls + 'cardHead',
          )}
          bodyStyle={{
            height: '75%',
            padding: '5px 0px',
            overflow: 'hidden',
          }}
          extra={
            <div style={{ padding: 0 }}>
              <AutoComplete
                options={autoOption}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                onSelect={onAutoSelect}
                className={prefixCls + 'CardAutoComplete-autoInput'}
              >
                <Input
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  placeholder="按名称搜索"
                  allowClear={true}
                />
              </AutoComplete>
            </div>
          }
        >
          <div
            className={prefixCls + 'infoRightViewRang'}
            style={{ height: '100%', paddingBottom: '10px' }}
          >
            <ScrollBarLayout
              style={{
                padding: '10px 10px 0px',
              }}
            >
              {receiveListMemo?.length > 0 ? (
                <div className={prefixCls + 'infoRightViewRang-detailCard'}>
                  {receiveListMemo?.map((item: any) => {
                    let receiveName: string =
                      item?.receiveDepartmentName +
                      (item?.receiveCompanyName
                        ? `（${item?.receiveCompanyName}）`
                        : '');
                    let showTitle = searchChangeStyle(
                      receiveName,
                      <MyIcon type={'icon-cluster'} />,
                    );
                    return (
                      <div
                        className={
                          prefixCls + 'infoRightViewRang-detailCardChild'
                        }
                        id={item?.receiveDepartmentID}
                        key={item?.receiveDepartmentID}
                      >
                        <div>{showTitle}</div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </ScrollBarLayout>
          </div>
        </Card>
      </div>
    </div>
  );
};
